package com.itheima.web;

import com.itheima.vo.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.ribbon.proxy.annotation.Hystrix;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.List;

@RestController
@RequestMapping("/consumer")
public class ConsumerController {
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @RequestMapping("/findUserById/v1/{id}")
    public User findUserByUserIdv1(@PathVariable Integer id){

        String url="http://127.0.0.1:9091/user/findUserById/"+id;
        User user = restTemplate.getForObject(url, User.class);
        return user;
    }

    /**
     * 使用discoveryClient调用
     * @param id
     * @return
     */
    @GetMapping("/findUserById/v2/{id}")
    public User findUserByIdv2(@PathVariable Integer id){
        List<ServiceInstance> instances = discoveryClient.getInstances("provider-service");
        ServiceInstance instance = instances.get(0);
        URI uri = instance.getUri();
        String url = uri + "/user/findUserById/" + id;
        System.out.println(url);
        return restTemplate.getForObject(url,User.class);
    }

    /**
     * 使用RestTemplate + ribbon 负载调用，注意不可使用ip调用，必须使用服务名
     * @param id
     * @return
     */
    @GetMapping("/findUserById/v3/{id}")
    @HystrixCommand(fallbackMethod = "fallMethod")
    public User findUserByIdv3(@PathVariable Integer id){
        String url = "http://provider-service/user/findUserById/" + id;
        System.out.println(url);
        return restTemplate.getForObject(url, User.class);
    }

    /**
     * 熔断方法，针对findUserByIdv3单个请求，参数需要一致
     * @param id
     * @return
     */
    public User fallMethod(Integer id){
        User user = new User();
        user.setId(id);
        user.setNote("熔断方法");
        return user;

    }
}
